package com.ikingtech.platform.service.oidc.endpoint.autorize;

import com.ikingtech.framework.sdk.utils.Tools;
import com.ikingtech.platform.service.oidc.endpoint.OidcEndpoint;
import com.ikingtech.platform.service.oidc.exception.InvalidRequestException;
import com.ikingtech.platform.service.oidc.exception.UnsupportedResponseTypeException;
import com.ikingtech.platform.service.oidc.web.OidcAuthorizationRequest;
import com.ikingtech.platform.service.oidc.web.OidcAuthorizationResponse;
import jakarta.servlet.http.HttpServletRequest;
import lombok.RequiredArgsConstructor;
import org.springframework.util.MultiValueMap;

import java.util.List;

/**
 * @author tie yan
 */
@RequiredArgsConstructor
public class DelegateOidcAuthorizeEndpoint implements OidcEndpoint {

    private final List<OidcAuthorizeEndpoint> authorizeEndpoints;

    @Override
    public OidcAuthorizationResponse authorization(HttpServletRequest request) {
        MultiValueMap<String, String> paramMap;

        if ("GET".equals(request.getMethod())) {
            paramMap = Tools.Http.getQueryParameters(request);
        } else if ("POST".equals(request.getMethod())) {
            paramMap = Tools.Http.getFormParameters(request);
        } else {
            throw new InvalidRequestException();
        }
        String responseType = paramMap.getFirst(OidcAuthorizationRequest.AuthenticationRequestFieldName.RESPONSE_TYPE);
        OidcAuthorizeEndpoint endpoint = null;
        for (OidcAuthorizeEndpoint authorizeEndpoint : this.authorizeEndpoints) {
            if (authorizeEndpoint.support(responseType)) {
                endpoint = authorizeEndpoint;
                break;
            }
        }
        if (null == endpoint) {
            throw new UnsupportedResponseTypeException();
        }
        return endpoint.authorization(paramMap);
    }

    @Override
    public boolean support(String requestUri) {
        return "/oidc/authorize".equals(requestUri);
    }
}
